import { createRouter, createWebHistory } from "vue-router";
import qs from "qs";
import routes from "./routes";
import { useUserStore } from "../store/user";
import { authConfig } from "./auth";
import { ElMessage } from "element-plus";

const router = createRouter({
  history: createWebHistory(),
  parseQuery: qs.parse,
  stringifyQuery: qs.stringify,
  routes,
});

router.beforeEach((to, from, next) => {
  console.log("router : " + from.fullPath + "=>" + to.fullPath);
  if (authConfig[to.name]) {
    if (authConfig[to.name].auth()) {
      // 权限通过
      next();
    } else {
      ElMessage({
        type: "info",
        message: authConfig[to.name].message || "没有权限",
      });
      if (authConfig[to.name].name) {
        next({
          name: authConfig[to.name].name,
        });
      } else if (authConfig[to.name].redirect) {
        next({
          path: authConfig[to.name].redirect
            ? authConfig[to.name].redirect
            : "/",
        });
      } else {
        next(false);
      }
    }
  } else {
    next();
  }
});

export default router;
